package com.hqs.listener.helper;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import com.hqs.common.utils.Log;

import java.lang.reflect.Type;
import java.util.ArrayList;

/**
 * Created by apple on 16/9/27.
 */

public class GsonHelper {

    private static Gson gson;

    public static void init(){
        gson = new Gson();
    }

    public static <T> ArrayList<T> parseArray(String jsonString, Class<T> klass){
        ArrayList<T> arrayList = null;
        try {
            Type type = (new TypeToken<ArrayList<LinkedTreeMap<String, String>>>(){}).getType();
            ArrayList<LinkedTreeMap> ts = gson.fromJson(jsonString, type);

            return parseArray(ts, klass);

        } catch (Exception e) {
            Log.print(jsonString);
            e.printStackTrace();
        }
        return arrayList;
    }

    public static <T> ArrayList<T> parseArray(ArrayList<LinkedTreeMap> array, Class<T> klass){

        ArrayList<T> arrayList = null;
        if(array != null && array.size() > 0){
            arrayList = new ArrayList<>();
            int len = array.size();
            for (int i = 0; i < len; i++) {
                arrayList.add(parseObject(array.get(i), klass));
            }
        }
        return arrayList;
    }

    public static <T> T parseObject(String jsonString, Class<T> c){
        try {
            return gson.fromJson(jsonString, c);
        } catch (Exception e) {
            Log.print(jsonString);
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T parseObject(LinkedTreeMap map, Class<T> c){
        String jsonString = gson.toJson(map);
        return parseObject(jsonString, c);
    }

    public static <T> String toJsonString(T t){
        return gson.toJson(t);
    }



}
